﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;

namespace Wsp365.Anonymous.AccessModifyWebPart
{
    [ToolboxItem(false)]
    public partial class AccessModifyWebPart : WebPart
    {
        private SPList list;
        protected HtmlGenericControl failure;
        protected HtmlGenericControl info;
        private static string discussionIncludeXsl = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:include href=\"{0}/Wsp365/Discussion/thread.xsl\"/></xsl:stylesheet>";
       
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string failureText = "";

            try
            {
                Guid listId = new Guid(Page.Request.Params["List"]);
                string webUrl = Page.Request.Params["WebUrl"];
                using (SPWeb web = SPContext.Current.Site.OpenWeb(webUrl, false))
                {
                    list = web.Lists[listId];

                    if (!web.AllowAnonymousAccess)
                    {
                        failureText = "Web does not allow anonymous access.";
                    }
                }
                lblTitle.Text = string.Format(lblTitle.Text, list.Title);
                if (!list.DoesUserHavePermissions(SPBasePermissions.ManageLists))
                {
                    failureText = "You are not allowed to manage permissions. ";
                    list = null;
                }
            }
            catch
            {
                failureText = "List not found.";
            }

            if (!String.IsNullOrEmpty(failureText))
            {
                lblTitle.ForeColor = System.Drawing.Color.Red;
                lblTitle.Font.Bold = true;
                lblTitle.Text = failureText;
                btnOk.Enabled = false;
                cbAnonymousAdd.Enabled = false;
                cbAnonymousEdit.Enabled = false;
                cbAnonymousRead.Enabled = false;
                cbEnableModeration.Enabled = false;
                info.Visible = false;
                failure.Visible = true;
            }
            if (list is SPDocumentLibrary)
            {
                cbAnonymousAdd.Enabled = false;
                cbAnonymousEdit.Enabled = false;
                cbEnableModeration.Enabled = false;
            }
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            SPBasePermissions additional = SPBasePermissions.EmptyMask;
            if (cbAnonymousAdd.Checked)
            {
                additional |= SPBasePermissions.AddListItems;
            }
            if (cbAnonymousEdit.Checked)
            {
                additional |= SPBasePermissions.EditListItems;
            }
            if (cbAnonymousRead.Checked)
            {
                additional |= SPBasePermissions.ViewListItems;
            }
            if (additional == SPBasePermissions.EmptyMask)
            {
                list.ResetRoleInheritance();
            }
            else
            {
                list.AddAnonymousAccess(additional);
            }

            if (cbEnableModeration.Checked)
            {
                if (!list.RootFolder.Properties.ContainsKey(ModerationEventReceiver.ModerationEventReceiver.PropertyName))
                {
                    list.RootFolder.AddProperty(ModerationEventReceiver.ModerationEventReceiver.PropertyName,
                        ModerationEventReceiver.ModerationEventReceiver.Enabled);
                    list.RootFolder.Update();
                }
                list.DraftVersionVisibility = DraftVisibilityType.Approver;
                list.EnableModeration = true;
                list.AddAnonymousAccess(list.AnonymousPermMask64 | SPBasePermissions.ManagePermissions);
                list.Update();
                //Set the moderated discussion thread view
                //Add an approval / deny button
                if (list.BaseTemplate == SPListTemplateType.DiscussionBoard
                    && list.Views.Count > 2)
                {
                    SPView flatView = list.Views[1];
                    flatView.Xsl = "<![CDATA[" + string.Format(discussionIncludeXsl, list.ParentWeb.Site.RootWeb.ServerRelativeUrl) + "]]>";
                    flatView.Update();
                }
            }
            else
            {
                if (list.RootFolder.Properties.ContainsKey(ModerationEventReceiver.ModerationEventReceiver.PropertyName))
                {
                    list.RootFolder.DeleteProperty(ModerationEventReceiver.ModerationEventReceiver.PropertyName);
                    list.RootFolder.Update();
                }
                list.AddAnonymousAccess((SPBasePermissions)((int)list.AnonymousPermMask64 - (int)SPBasePermissions.ManagePermissions));
                list.DraftVersionVisibility = DraftVisibilityType.Reader;
                list.EnableModeration = false;
                list.Update();
                //remove the approval / deny button
                if (list.BaseTemplate == SPListTemplateType.DiscussionBoard
                    && list.Views.Count > 2)
                {
                    SPView flatView = list.Views[1];
                    flatView.Xsl = "";
                    flatView.Update();
                }
            }

            HtmlGenericControl hgc = new HtmlGenericControl("script");
            hgc.Attributes.Add("type", "text/javascript");
            hgc.InnerHtml = @"SP.SOD.executeOrDelayUntilScriptLoaded(dialogOkCommit, 'sp.js'); 
            function dialogOkCommit()
            {
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK);
            }";
            Controls.Add(hgc);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (list != null && !Page.IsPostBack && list.HasUniqueRoleAssignments)
            {
                SPBasePermissions currentPermission = list.AnonymousPermMask64;
                cbAnonymousAdd.Checked = (currentPermission & SPBasePermissions.AddListItems) == SPBasePermissions.AddListItems;
                cbAnonymousEdit.Checked = (currentPermission & SPBasePermissions.EditListItems) == SPBasePermissions.EditListItems;
                cbAnonymousRead.Checked = (currentPermission & SPBasePermissions.ViewListItems) == SPBasePermissions.ViewListItems;
                cbEnableModeration.Checked = list.RootFolder.Properties.ContainsKey(ModerationEventReceiver.ModerationEventReceiver.PropertyName)
                && ModerationEventReceiver.ModerationEventReceiver.Enabled.Equals(list.RootFolder.Properties[ModerationEventReceiver.ModerationEventReceiver.PropertyName]);
             }
        }
    }
}
